package com.sxg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxg.convert.ConvertUtils;
import com.sxg.convert.SxgAddressConvert;
import com.sxg.dao.SxgAddressDao;
import com.sxg.entity.SxgAddressEntity;
import com.sxg.enums.ResultCodeEnum;
import com.sxg.query.SxgAddressQuery;
import com.sxg.service.SxgAddressService;
import com.sxg.utils.SecurityUtils;
import com.sxg.utils.StringUtils;
import com.sxg.utils.code.AjaxResult;
import com.sxg.vo.SxgAddressVO;
import com.sxg.vo.req.AddressSaveReqVo;
import com.sxg.vo.resp.AddressRespVo;
import lombok.AllArgsConstructor;
import com.sxg.page.PageResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.sxg.page.PageResult;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 地址表
 *
 * @author 浪漫写尽歌谱 3298751420@qq.com
 * @since 1.0.0 2024-03-07
 */
@Service
@AllArgsConstructor
public class SxgAddressServiceImpl extends ServiceImpl<SxgAddressDao, SxgAddressEntity> implements SxgAddressService {

    @Override
    public PageResult<SxgAddressVO> page(SxgAddressQuery query) {
        IPage<SxgAddressEntity> page = baseMapper.selectPage(PageResult.getPage(query), getWrapper(query));

        return new PageResult<>(SxgAddressConvert.INSTANCE.convertList(page.getRecords()), page.getTotal());
    }

    private LambdaQueryWrapper<SxgAddressEntity> getWrapper(SxgAddressQuery query) {
        LambdaQueryWrapper<SxgAddressEntity> wrapper = Wrappers.lambdaQuery();
        return wrapper;
    }

    @Override
    public void save(AddressSaveReqVo vo) {
        SxgAddressEntity entity = ConvertUtils.toSxgAddressEntity(vo);
        entity.setUserId(SecurityUtils.getUserId());
        baseMapper.insert(entity);
        if ("1".equals(entity.getIsDefault())) {
            //取消原来的默认地址
            Long userId = SecurityUtils.getUserId();
            SxgAddressEntity newAddress = new SxgAddressEntity();
            newAddress.setIsDefault("0");
            getBaseMapper().update(newAddress, Wrappers.<SxgAddressEntity>lambdaUpdate().eq(SxgAddressEntity::getIsDefault, "1").eq(SxgAddressEntity::getUserId, userId));
        }
    }

    @Override
    public AjaxResult update(SxgAddressVO vo) {
        SxgAddressEntity entity = SxgAddressConvert.INSTANCE.convert(vo);
        //检查当前设置地址是否存在
        SxgAddressEntity sxgAddressEntity = baseMapper.selectOne(Wrappers.<SxgAddressEntity>lambdaQuery().select(SxgAddressEntity::getId).eq(SxgAddressEntity::getId, entity.getId()));
        if (StringUtils.isNull(sxgAddressEntity)) {
            return AjaxResult.error(ResultCodeEnum.ADDRESS_NOT_EXIST.getCode(), ResultCodeEnum.ADDRESS_NOT_EXIST.getMessage());
        }
        //检查当前设置地址是否是默认地址
        if (entity.getIsDefault() != null && "1".equals(entity.getIsDefault())) {
            //取消原来的默认地址
            Long userId = SecurityUtils.getUserId();
            SxgAddressEntity newAddress = new SxgAddressEntity();
            newAddress.setIsDefault("0");
            getBaseMapper().update(newAddress, Wrappers.<SxgAddressEntity>lambdaUpdate().eq(SxgAddressEntity::getIsDefault, "1").eq(SxgAddressEntity::getUserId, userId));
        }
        updateById(entity);
        return AjaxResult.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult delete(Long id) {
        SxgAddressEntity entity = baseMapper.selectOne(Wrappers.<SxgAddressEntity>lambdaQuery().select(SxgAddressEntity::getId).eq(SxgAddressEntity::getId, id).eq(SxgAddressEntity::getUserId, SecurityUtils.getUserId()).eq(SxgAddressEntity::getIsDefault, "1"));
        if (entity != null) {
            return AjaxResult.error("默认地址不能删除");
        }
        baseMapper.deleteById(id);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult selectByIdList() {
        Long userId = SecurityUtils.getUserId();
        List<SxgAddressEntity> sxgAddressEntities = baseMapper.selectList(Wrappers.<SxgAddressEntity>lambdaQuery().eq(SxgAddressEntity::getUserId, userId));
        List<AddressRespVo> respVos = sxgAddressEntities.stream().map(this::getAddressRespVo).collect(Collectors.toList());
        return AjaxResult.success(respVos);
    }

    private AddressRespVo getAddressRespVo(SxgAddressEntity sxgAddressEntity) {
        AddressRespVo addressRespVo = new AddressRespVo();
        addressRespVo.setId(sxgAddressEntity.getId());
        addressRespVo.setName(sxgAddressEntity.getName());
        addressRespVo.setPhone(sxgAddressEntity.getPhone());
        addressRespVo.setIsDefault(sxgAddressEntity.getIsDefault());
        addressRespVo.setCity(sxgAddressEntity.getCity());
        addressRespVo.setProvince(sxgAddressEntity.getProvince());
        addressRespVo.setCountry(sxgAddressEntity.getCountry());
        addressRespVo.setDetail(sxgAddressEntity.getDetail());
        return addressRespVo;
    }

    @Override
    public AjaxResult setDefaultAddress(Long id) {
        if (StringUtils.isNull(id)) {
            return AjaxResult.error("地址id不能为空");
        }
        //检查当前设置地址是否存在
        SxgAddressEntity sxgAddressEntity = baseMapper.selectOne(Wrappers.<SxgAddressEntity>lambdaQuery().select(SxgAddressEntity::getId).eq(SxgAddressEntity::getId, id));
        if (StringUtils.isNull(sxgAddressEntity)) {
            return AjaxResult.error(ResultCodeEnum.ADDRESS_NOT_EXIST.getCode(), ResultCodeEnum.ADDRESS_NOT_EXIST.getMessage());
        }

        //如果设置的与原本的一样直接返回
        if (id.equals(sxgAddressEntity.getId())) {
            return AjaxResult.success();
        }

        Long userId = SecurityUtils.getUserId();

        //取消原来的默认地址
        SxgAddressEntity newAddress = new SxgAddressEntity();
        newAddress.setIsDefault("0");
        getBaseMapper().update(newAddress, new LambdaUpdateWrapper<SxgAddressEntity>().eq(SxgAddressEntity::getIsDefault, "1").eq(SxgAddressEntity::getUserId, userId));

        //设置新的默认值
        SxgAddressEntity addressEntity = new SxgAddressEntity();
        sxgAddressEntity.setIsDefault("1");
        addressEntity.setId(id);
        updateById(addressEntity);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult selectById(Long id) {
        SxgAddressEntity sxgAddressEntity = baseMapper.selectOne(Wrappers.<SxgAddressEntity>lambdaQuery().eq(SxgAddressEntity::getId, id));
        AddressRespVo addressRespVo = getAddressRespVo(sxgAddressEntity);
        return AjaxResult.success(addressRespVo);
    }

    @Override
    public AjaxResult getDefaultAddress() {
        Long userId = SecurityUtils.getUserId();
        SxgAddressEntity entity = getBaseMapper().selectOne(Wrappers.<SxgAddressEntity>lambdaQuery().eq(SxgAddressEntity::getIsDefault, "1").eq(SxgAddressEntity::getUserId, userId));
        if (entity == null) {
            List<SxgAddressEntity> sxgAddressEntities = getBaseMapper().selectList(Wrappers.<SxgAddressEntity>lambdaQuery().eq(SxgAddressEntity::getUserId, userId));
            entity = sxgAddressEntities.get(0);
        }
        return AjaxResult.success(entity);
    }

}